package com.hbnu;


import com.hbnu.*;

import java.util.*;

public class FlowerShopService {
    private final FlowerDao flowerDao = new FlowerDao();
    private final CustomerDao customerDao = new CustomerDao();
    private final OrderDao orderDao = new OrderDao();
    private final OrderDetailDao orderDetailDao = new OrderDetailDao();
    private final Scanner sc = new Scanner(System.in);

    /** 查看所有花卉 */
    public void showAllFlowers() {
        System.out.println("\n🌸 当前花卉库存如下：");
        List<Flower> flowers = flowerDao.getAllFlowers();
        if (flowers.isEmpty()) {
            System.out.println("❌ 当前没有花卉记录");
            return;
        }
        flowers.forEach(System.out::println);
    }

    /** 添加花卉 */
    public void addFlower() {
        System.out.println("\n🌹 添加新花卉");
        System.out.print("输入花名: "); String name = sc.next();
        System.out.print("输入类型: "); String type = sc.next();
        System.out.print("输入价格: "); double price = sc.nextDouble();
        System.out.print("输入库存: "); int stock = sc.nextInt();
        System.out.print("输入描述: "); String desc = sc.next();

        Flower flower = new Flower(name, type, price, stock, desc);
        if (flowerDao.addFlower(flower)) {
            System.out.println("✅ 添加成功！");
        } else {
            System.out.println("❌ 添加失败！");
        }
    }

    /** 查看客户列表 */
    public void listCustomers() {
        System.out.println("\n👤 客户列表：");
        List<Customer> customers = customerDao.getAllCustomers();
        if (customers.isEmpty()) {
            System.out.println("❌ 当前没有客户记录");
            return;
        }
        customers.forEach(System.out::println);
    }

    /** 添加客户 */
    public void addCustomer() {
        System.out.println("\n👥 添加新客户");
        System.out.print("输入姓名: "); String name = sc.next();
        System.out.print("输入电话: "); String phone = sc.next();
        sc.nextLine(); // 清除缓冲区
        System.out.print("输入地址: "); String address = sc.nextLine();

        Customer customer = new Customer(name, phone, address);
        if (customerDao.addCustomer(customer)) {
            System.out.println("✅ 客户添加成功！");
        } else {
            System.out.println("❌ 客户添加失败！");
        }
    }

    /** 客户下单购买 */
    public void buyFlower() {
        System.out.println("\n🛒 客户下单");
        listCustomers();
        System.out.print("选择客户ID: ");
        int customerId = sc.nextInt();

        Customer customer = customerDao.getCustomerById(customerId);
        if (customer == null) {
            System.out.println("❌ 客户不存在！");
            return;
        }

        System.out.println("\n🌸 可选花卉：");
        showAllFlowers();

        double total = 0;
        Map<Integer, Integer> cart = new HashMap<>(); // 花卉ID -> 数量

        while (true) {
            System.out.print("输入要购买的花卉ID（输入0结束）: ");
            int fid = sc.nextInt();
            if (fid == 0) break;

            Flower f = flowerDao.getFlowerById(fid);
            if (f == null) {
                System.out.println("❌ 没找到此花！");
                continue;
            }

            System.out.print("输入购买数量: ");
            int qty = sc.nextInt();

            if (qty > f.getStock()) {
                System.out.println("❌ 库存不足！");
                continue;
            }

            // 更新库存和销量
            boolean ok = flowerDao.updateStockAndSoldCount(fid, qty);
            if (!ok) {
                System.out.println("❌ 更新库存失败！");
                continue;
            }

            cart.put(fid, cart.getOrDefault(fid, 0) + qty);
            double sub = f.getPrice() * qty;
            total += sub;
            System.out.println("✅ 已加入购物车，小计: " + sub);
        }

        if (cart.isEmpty()) {
            System.out.println("🛒 未选择任何商品，已取消下单。");
            return;
        }

        // 生成订单
        Order order = new Order(customerId, total);
        int orderId = orderDao.createOrder(order);

        if (orderId != -1) {
            // 生成订单明细
            for (Map.Entry<Integer, Integer> entry : cart.entrySet()) {
                int fid = entry.getKey();
                int qty = entry.getValue();
                Flower f = flowerDao.getFlowerById(fid);
                OrderDetail detail = new OrderDetail(orderId, fid, qty, f.getPrice() * qty);
                orderDetailDao.addOrderDetail(detail);
            }
            System.out.println("✅ 下单完成，订单号: " + orderId + "，总金额: " + total);
        } else {
            System.out.println("❌ 订单生成失败！");
        }
    }

    /** 查看销售统计 */
    public void showSalesReport() {
        System.out.println("\n📊 销售统计报告：");
        System.out.printf("%-5s %-10s %-10s %-10s\n", "ID", "花卉", "已售数量", "销售额");
        for (Flower f : flowerDao.getAllFlowers()) {
            double sale = f.getPrice() * f.getSoldCount();
            System.out.printf("%-5d %-10s %-10d %-10.2f\n",
                    f.getId(), f.getName(), f.getSoldCount(), sale);
        }
    }

    /** 查看订单列表 */
    public void showAllOrders() {
        System.out.println("\n📋 所有订单：");
        List<Order> orders = orderDao.getAllOrders();
        if (orders.isEmpty()) {
            System.out.println("❌ 当前没有订单记录");
            return;
        }
        orders.forEach(System.out::println);
    }

    /** 查看订单明细 */
    public void showOrderDetails() {
        showAllOrders();
        System.out.print("输入要查看的订单ID: ");
        int orderId = sc.nextInt();

        List<OrderDetail> details = orderDetailDao.getDetailsByOrderId(orderId);
        if (details.isEmpty()) {
            System.out.println("❌ 该订单没有明细或订单不存在");
            return;
        }

        System.out.println("📦 订单明细：");
        details.forEach(System.out::println);
    }

    /** 搜索花卉 */
    public void searchFlowers() {
        System.out.print("输入搜索关键词: ");
        String keyword = sc.next();

        List<Flower> results = flowerDao.searchFlowers(keyword);
        if (results.isEmpty()) {
            System.out.println("❌ 没有找到相关花卉");
            return;
        }

        System.out.println("🔍 搜索结果：");
        results.forEach(System.out::println);
    }

    /** 库存预警 */
    public void showLowStockAlert() {
        System.out.print("输入库存预警阈值: ");
        int threshold = sc.nextInt();

        List<Flower> lowStockFlowers = flowerDao.getLowStockFlowers(threshold);
        if (lowStockFlowers.isEmpty()) {
            System.out.println("✅ 所有花卉库存充足");
            return;
        }

        System.out.println("⚠️  低库存预警：");
        lowStockFlowers.forEach(System.out::println);
    }
}
